require("dotenv").config();
const express = require("express");
const router = express.Router();
const passport = require("passport");
const path = require("path");
const fs = require("fs");
const upload = require("../../middlewares/upLoad");
const errorHandler = require("../../middlewares/errorHandler");
const OpenApi = require("@alicloud/openapi-client");
const Util = require("@alicloud/tea-util");
const Stream = require("@alicloud/darabonba-stream");

const auth = passport.authenticate("jwt", { session: false });

class AliyunClient {
  static createClient() {
    const accessKeyId = process.env["ALIBABA_CLOUD_ACCESS_KEY_ID"];
    const accessKeySecret = process.env["ALIBABA_CLOUD_ACCESS_KEY_SECRET"];

    if (!accessKeyId || !accessKeySecret) {
      throw new Error(
        "请设置 ALIBABA_CLOUD_ACCESS_KEY_ID 和 ALIBABA_CLOUD_ACCESS_KEY_SECRET 环境变量"
      );
    }

    return new OpenApi.default(
      new OpenApi.Config({
        accessKeyId,
        accessKeySecret,
        endpoint: "ocr-api.cn-hangzhou.aliyuncs.com",
      })
    );
  }

  static createApiInfo() {
    return new OpenApi.Params({
      action: "RecognizeCarNumber",
      version: "2021-07-07",
      protocol: "HTTPS",
      method: "POST",
      authType: "AK",
      style: "V3",
      pathname: "/",
      reqBodyType: "json",
      bodyType: "json",
    });
  }

  static async recognizeCarNumber(filePath) {
    const client = AliyunClient.createClient();
    const params = AliyunClient.createApiInfo();
    const body = Stream.default.readFromFilePath(filePath);
    const request = new OpenApi.OpenApiRequest({ stream: body });
    const runtime = new Util.RuntimeOptions({});

    return await client.callApi(params, request, runtime);
  }
}

router.post("/addfiles", auth, upload.array("files", 3), async (req, res) => {
  try {
    if (!req.files || req.files.length === 0) {
      return res.status(400).json({ success: false, error: "文件上传失败" });
    }

    const recognitionResults = await Promise.all(
      req.files.map(async (file) => {
        const filePath = path.join(
          __dirname,
          "../../public/uploads/",
          file.filename
        );
        const recognitionResult = await AliyunClient.recognizeCarNumber(
          filePath
        );

        const parsedData = JSON.parse(recognitionResult.body.Data || "{}");
        const carType =
          parsedData.structure_list?.[0]?.secondary_cls?.type_str || "未知";
        const carPlate = parsedData.structure_list?.[0]?.data?.车牌 || "未知";

        return {
          fileUrl: `${req.protocol}://${req.get("host")}/${file.filename}`,
          carType,
          carPlate,
        };
      })
    );

    console.log("文件上传和识别成功", recognitionResults);
    res.status(200).json({ success: true, recognitionResults });
  } catch (err) {
    errorHandler(res, err);
  }
});

router.delete("/deletefile", auth, (req, res) => {
  try {
    const { filename } = req.body;
    const filePath = path.join(__dirname, "../../public/uploads/", filename);

    if (!fs.existsSync(filePath)) {
      return res.status(404).json({ success: false, error: "未找到该文件" });
    }

    fs.unlinkSync(filePath);
    console.log("文件删除成功:", filename);
    res.status(200).json({ success: true, message: "文件删除成功" });
  } catch (err) {
    errorHandler(res, err);
  }
});

module.exports = router;
